package cn.cjxy.controller;

import cn.cjxy.domain.User;
import cn.cjxy.service.UserService;
import cn.cjxy.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 完成控制层的基本CRUD
 */
@RequestMapping("/user")
@RestController
public class UserController {
    //注入service
    @Autowired
    private UserService userService;

    //新增和修改
    @PostMapping
    public String addOrSaveUser(@RequestBody User user) {//将前端的json格式对象 封装到user中
        boolean b = userService.saveOrUpdate(user);
        if (b){
            return "success";
        }else {
            return "fail";
        }
    }

    //查询
    @GetMapping
    public List<User> findAllUser() {
        return userService.list();
    }

    //分页查询（前端传递当前页码，和每个页面的条数两个参数过来，调用service方法完成分页查询返回符合条件的数据给前端）
    @PostMapping("/page")
    public List<User> findUsersPage(@RequestBody UserVo userVo){
        //封装页面信息
        Page<User> userPage = new Page<>(userVo.getCurrentPage(), userVo.getPageSize());
        //查询信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name",userVo.getKeywords());
        //执行查询 获取记录
        return userService.page(userPage,userQueryWrapper).getRecords();

    }


    //根据id删除
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id") Integer id) {
        if(userService.removeById(id)) {
            return "success";
        }else {
            return "fail";
        }
    }

    //通过id查询
    @GetMapping("/{id}")
    public User findUserById(@PathVariable("id") Integer id) {
        return userService.getById(id);
    }

    //登录
    @PostMapping("/login")
    public User login(@RequestBody User user) {
       return userService.login(user);
    }
}
